<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据银行：HTTP计算机</title>
    <style>
        :root {
            --color-bg-dark: #121217;
            --color-bg-medium: #1F1F2A;
            --color-bg-light: #2A2A38;
            --color-element-bg: #353545;
            --color-border-subtle: #404055;
            --color-text-main: #E0E0E0;
            --color-text-subtle: #A0A0B0;

            --color-accent-blue-low: #6F9BBF;
            --color-accent-green-low: #7BBF9F;
            --color-error: #D96666;
            --color-highlight-gold: #E0D06B;
            --color-system-note-bg: #3D4C4F;
            --color-system-note-link: #CCE8F5;
        }

        body {
            font-family: 'Fira Code', 'JetBrains Mono', 'SF Mono', Consolas, 'Courier New', monospace;
            margin: 0;
            padding: 20px;
            background-color: var(--color-bg-dark);
            color: var(--color-text-main);
            line-height: 1.6;
            display: flex;
            justify-content: center;
            overflow-y: scroll;
        }

        .container {
            background-color: var(--color-bg-medium);
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.6);
            max-width: 1200px;
            width: 100%;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
        }

        h1 {
            color: var(--color-accent-green-low);
            text-align: center;
            margin-bottom: 20px;
            font-size: 2.2em;
        }

        h2 {
            color: var(--color-accent-blue-low);
            border-bottom: 1px solid var(--color-border-subtle);
            padding-bottom: 8px;
            font-size: 1.6em;
        }

        h3 {
            margin-top: 25px;
            margin-bottom: 15px;
            color: var(--color-text-main);
        }

        p {
            margin-bottom: 10px;
            color: var(--color-text-subtle);
        }

        .description {
            color: var(--color-text-subtle);
            text-align: center;
            margin-bottom: 25px;
            line-height: 1.8;
        }

        section {
            margin-bottom: 30px;
            padding: 20px;
            background-color: var(--color-bg-light);
            border-radius: 6px;
            border-left: 3px solid var(--color-accent-blue-low);
        }

        input[type="text"],
        input[type="number"] {
            padding: 10px 12px;
            border: 1px solid var(--color-border-subtle);
            border-radius: 44px;
            background-color: var(--color-element-bg);
            color: var(--color-text-main);
            margin-right: 10px;
            margin-bottom: 10px;
            box-sizing: border-box;
            font-family: inherit;
            font-size: 0.9em;
        }

        input[type="number"] {
            -moz-appearance: textfield;
            width: calc(25% - 20px);
        }
        input[type="number"]::-webkit-outer-spin-button,
        input[type="number"]::-webkit-inner-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }

        button {
            background-color: var(--color-accent-green-low);
            color: var(--color-bg-dark);
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 0.95em;
            margin-right: 10px;
            transition: background-color 0.2s ease, transform 0.1s ease;
            font-weight: bold;
        }

        button:hover {
            background-color: #92D4B6;
            transform: translateY(-1px);
        }
        button:active {
            transform: translateY(0);
        }

        .highlight {
            color: var(--color-accent-blue-low);
            font-weight: bold;
        }
        code.highlight {
            color: var(--color-highlight-gold);
            background-color: rgba(255, 255, 255, 0.05);
            padding: 2px 5px;
            border-radius: 3px;
        }

        #loginStatus, #bankResult {
            margin-top: 15px;
            font-weight: bold;
            color: var(--color-text-main);
        }
        #bankResult.error {
            color: var(--color-error);
        }
        #loginStatus.first-time {
            color: var(--color-highlight-gold);
        }
        #loginStatus.revisit {
            color: var(--color-accent-blue-low);
        }

        .input-group {
            margin-bottom: 15px;
            display: flex;
            flex-wrap: wrap;
            align-items: center;
        }
        .input-group label {
            min-width: 60px;
            margin-right: 5px;
            color: var(--color-text-subtle);
        }

        .memory-interface-layout {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-top: 20px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .memory-viewer-wrapper {
            display: flex;
            align-items: flex-start;
            gap: 10px;
            border: 2px solid var(--color-border-subtle);
            padding: 8px;
            background-color: var(--color-element-bg);
            border-radius: 3px;
            box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.4);
            width: fit-content;
            margin: 0 auto;
        }

        .memory-column {
            font-size: 0.8em;
            color: var(--color-text-subtle);
            user-select: none;
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
        }

        .memory-address-column {
            text-align: right;
            width: 60px;
            font-family: 'Fira Code', 'JetBrains Mono', 'SF Mono', Consolas, 'Courier New', monospace;
            flex-shrink: 0;
        }

        .memory-ascii-column {
            text-align: left;
            width: 120px;
            font-family: 'Fira Code', 'JetBrains Mono', 'SF Mono', Consolas, 'Courier New', monospace;
            white-space: pre;
            flex-shrink: 0;
        }

        .memory-row-address, .memory-row-ascii {
            height: 44px;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            padding-right: 5px;
            padding-left: 5px;
        }
        .memory-row-address:not(:last-child), .memory-row-ascii:not(:last-child) {
            border-bottom: 1px solid var(--color-border-subtle);
        }

        .memory-grid-container {
            flex: none;
            min-width: unset;
            padding: 0;
        }

        .memory-grid {
            display: grid;
            grid-template-columns: repeat(16, 1fr);
            gap: 4px;
            border: none;
            padding: 0;
            background-color: transparent;
            box-shadow: none;
        }

        .memory-box {
            width: 40px;
            height: 40px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            background-color: var(--color-element-bg);
            border: 1px solid #5A5A6E;
            border-radius: 4px;
            font-size: 0.75em;
            color: var(--color-text-subtle);
            position: relative;
            box-sizing: border-box;
            transition: background-color 0.15s ease, border-color 0.15s ease, box-shadow 0.15s ease;
            cursor: pointer;
            box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.3);
            background: linear-gradient(135deg, var(--color-element-bg) 0%, #2F2F3B 100%);
            overflow: hidden;
        }

        /* 移除原有的 memory-box:hover 样式，因为它会被下面的 current-address/hover 覆盖 */
        /* .memory-box:hover {
            background-color: #404050;
            border-color: #808090;
            box-shadow: inset 0 0 8px rgba(0, 0, 0, 0.4), 0 0 5px rgba(255, 255, 255, 0.1);
        } */

        .box-address {
            display: none;
        }

        .memory-box .box-value {
            font-size: 0.9em;
            color: var(--color-text-main);
            font-weight: bold;
            text-align: center;
            line-height: 1;
        }

        .memory-box .key-indicators {
            position: absolute;
            bottom: 2px;
            right: 2px;
            display: flex;
            gap: 1px;
        }

        .memory-box .key-indicators span {
            width: 4px;
            height: 8px;
            background-color: var(--color-border-subtle);
            border-radius: 1px;
            opacity: 0.5;
            transition: background-color 0.1s ease, opacity 0.1s ease;
        }

        .private-box.current-user {
            border-color: var(--color-accent-blue-low);
            background: linear-gradient(135deg, #2F3542 0%, #22252C 100%);
        }
        .private-box.current-user:hover {
            background: linear-gradient(135deg, #3C455A 0%, #2A303A 100%);
        }
        .private-box.current-user.current-address .key-indicators span {
            opacity: 1;
        }
        .private-box.current-user.current-address .key-indicators .key-manage { background-color: var(--color-accent-blue-low); }
        .private-box.current-user.current-address .key-indicators .key-read { background-color: var(--color-accent-green-low); }
        .private-box.current-user.current-address.key-write { background-color: var(--color-error); }


        .current-address, /* 保持原有的 current-address 样式 */
        .memory-box:hover { /* 新增：鼠标悬停时的视觉效果与 current-address 相同 */
            border: 2px solid var(--color-highlight-gold) !important;
            box-shadow: inset 0 0 10px rgba(224, 208, 107, 0.4), 0 0 10px rgba(var(--color-highlight-gold), 0.6) !important;
            background: linear-gradient(135deg, #4A4A5A 0%, #3A3A4A 100%) !important;
        }


        .update-note {
            background-color: var(--color-system-note-bg);
            color: var(--color-text-main);
            padding: 18px 25px;
            margin-bottom: 25px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
            font-size: 1.05em;
            font-weight: normal;
            line-height: 1.5;
            border-left: 4px solid var(--color-accent-green-low);
        }
        .update-note h3 {
            color: var(--color-accent-green-low);
            margin-top: 0;
            margin-bottom: 12px;
            font-size: 1.4em;
        }
        .update-note p {
            margin-bottom: 8px;
            color: var(--color-text-subtle);
        }
        .update-note ul {
            list-style: none;
            padding: 0;
            margin: 15px 0;
            text-align: left;
            color: var(--color-text-subtle);
        }
        .update-note ul li {
            margin-bottom: 5px;
            padding-left: 20px;
            position: relative;
        }
        .update-note ul li::before {
            content: '✓';
            color: var(--color-accent-green-low);
            position: absolute;
            left: 0;
            top: 0;
            font-weight: bold;
        }
        .update-note a {
            color: var(--color-system-note-link);
            text-decoration: underline;
            transition: color 0.2s ease;
        }
        .update-note a:hover {
            color: var(--color-highlight-gold);
        }

        /* 恢复并修改数据监视器样式 */
        .data-monitor-floating-wrapper {
            position: fixed; /* 浮动定位 */
            z-index: 1000; /* 确保在最上层 */
            width: 280px; /* 固定宽度，防止内容抖动 */
            /* top and left will be set by JavaScript */
            top: 0; left: 0;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.2s ease, transform 0.1s ease; /* 平滑显示/隐藏，平滑跟随 */
            pointer-events: none; /* 关键：不阻挡下方元素的点击事件 */
            transform: translate(20px, 20px); /* 默认偏移，防止监视器盖住鼠标 */
        }
        .data-monitor-floating-wrapper.visible {
            opacity: 1;
            visibility: visible;
        }

        .data-monitor {
            background-color: var(--color-bg-light);
            border: 1px solid var(--color-border-subtle);
            border-radius: 4px;
            padding: 15px;
            box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2); /* 内阴影模拟屏幕凹陷感 */
            min-height: 150px;
            font-size: 0.85em;
            line-height: 1.5;
            color: var(--color-text-main);
            overflow-x: auto; /* 允许内容横向滚动 */
        }
        .data-monitor h4 {
            margin-top: 0;
            margin-bottom: 10px;
            color: var(--color-accent-blue-low);
            font-size: 1.1em;
            border-bottom: 1px dashed var(--color-border-subtle); /* 虚线更符合数据流 */
            padding-bottom: 5px;
        }
        .data-monitor p {
            margin: 5px 0;
            color: var(--color-text-subtle);
        }
        .data-monitor .monitor-value, .data-monitor .monitor-hex, .data-monitor .monitor-ascii {
            color: var(--color-text-main);
            font-weight: bold;
        }
        .data-monitor .monitor-address { color: var(--color-accent-blue-low); }
        .data-monitor .monitor-hex { color: var(--color-highlight-gold); }
        .data-monitor .monitor-ascii { color: var(--color-accent-green-low); }
        .data-monitor .permission-status {
            color: var(--color-accent-green-low);
            font-weight: bold;
            margin-top: 8px;
            display: block;
        }
        .data-monitor .permission-status.red {
            color: var(--color-error);
        }

        @media (max-width: 900px) {
            .memory-viewer-wrapper {
                flex-direction: column;
                align-items: center;
                width: 100%;
            }
            .memory-column {
                width: 100%;
                text-align: center;
                display: flex;
                flex-wrap: wrap;
                justify-content: center;
                gap: 8px;
                padding: 5px 0;
            }
            .memory-row-address, .memory-row-ascii {
                height: auto;
                padding: 5px 10px;
                border: 1px solid var(--color-border-subtle);
                border-radius: 4px;
                background-color: var(--color-element-bg);
                align-items: center;
                display: flex;
                flex-shrink: 0;
                margin-bottom: 8px;
            }
            .memory-row-address:not(:last-child), .memory-row-ascii:not(:last-child) {
                border-bottom: none;
            }
            .memory-address-column > div:last-child,
            .memory-ascii-column > div:last-child {
                margin-bottom: 0;
            }
            .memory-address-column {
                order: 1;
            }
            .memory-grid-container {
                order: 2;
                width: auto;
                margin: 0 auto;
            }
            .memory-ascii-column {
                order: 3;
            }
            /* 小屏幕下隐藏浮动监视器，因为它会干扰布局 */
            .data-monitor-floating-wrapper {
                display: none;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>数据银行：HTTP计算机 <span style="font-size: 1rem;"> Last update at: 2025-09-14 20:18:25 （<a href="readme.html" target="_blank" rel="noopener noreferrer" style="color: #ddd;">说明</a>）</span></h1>

        <section id="login-section">
            <h2>用户身份</h2>
            <button onclick="clearUserId()">清除用户ID</button>
            <p id="loginStatus"></p>
            <p>用户 ID: <span id="userIdDisplay" class="highlight">未识别</span></p>
            <p>私有地址范围: <span id="privateRangeDisplay" class="highlight">0 ~ 511</span></p>
        </section>

        <section id="my-data-safe-section">
            <h2>私有内存</h2>

            <div class="memory-interface-layout">
                <div class="memory-viewer-wrapper">
                    <div id="memoryAddressColumn" class="memory-column memory-address-column">
                    </div>
                    <div class="memory-grid-container">
                        <div id="privateMemoryGrid" class="memory-grid">
                        </div>
                    </div>
                    <div id="memoryAsciiColumn" class="memory-column memory-ascii-column">
                    </div>
                </div>
            </div>

            <h3>单字节操作</h3>
            <div class="input-group">
                <label for="bankAddress">地址:</label>
                <input type="number" id="bankAddress" value="0" min="0" max="511">
                <label for="bankValue">值 (0-255):</label>
                <input type="number" id="bankValue" min="0" max="255" value="65">
            </div>
            <button id="writeButton">写入</button>
            <p>结果: <span id="bankResult" class="highlight"></span></p>
        </section>

    </div>

    <!-- Re-added Data Monitor for floating behavior -->
    <div id="dataMonitorFloatingWrapper" class="data-monitor-floating-wrapper">
        <div id="dataMonitor" class="data-monitor">
            <h4>数据监视器</h4>
            <p>地址: <span class="monitor-address">未选择</span></p>
            <p>十进制值: <span class="monitor-value">N/A</span></p>
            <p>十六进制值: <span class="monitor-hex">N/A</span></p>
            <p>ASCII字符: <span class="monitor-ascii">N/A</span></p>
            <hr style="border-color: var(--color-border-subtle); margin: 15px 0;">
            <h4>权限状态</h4>
            <p><span class="permission-status red">未选择单元</span></p>
        </div>
    </div>

    <script>
        const USER_ID_STORAGE_KEY = 'stored_user_id';
        const BYTE_STORAGE_PREFIX = 'data_bank_byte_';
        const PRIVATE_RANGE_START = 0;
        const INITIAL_PRIVATE_BOXES_SIZE = 512;
        const PRIVATE_RANGE_END = PRIVATE_RANGE_START + INITIAL_PRIVATE_BOXES_SIZE - 1;

        let currentUserId = null;
        let selectedAddress = PRIVATE_RANGE_START;
        let isMonitorVisible = false; // Track monitor visibility

        const loginStatus = document.getElementById('loginStatus');
        const userIdDisplay = document.getElementById('userIdDisplay');
        const privateRangeDisplay = document.getElementById('privateRangeDisplay');

        const bankAddressInput = document.getElementById('bankAddress');
        const bankValueInput = document.getElementById('bankValue');
        const writeButton = document.getElementById('writeButton');
        const bankResult = document.getElementById('bankResult');

        const privateMemoryGrid = document.getElementById('privateMemoryGrid');
        const memoryAddressColumn = document.getElementById('memoryAddressColumn');
        const memoryAsciiColumn = document.getElementById('memoryAsciiColumn');

        // Re-added Data Monitor DOM elements
        const dataMonitorFloatingWrapper = document.getElementById('dataMonitorFloatingWrapper');
        const dataMonitor = document.getElementById('dataMonitor');
        const memoryViewerWrapper = document.querySelector('.memory-viewer-wrapper'); // 获取整个内存显示区域的父容器

        function decToHex(dec) {
            return dec.toString(16).toUpperCase().padStart(2, '0');
        }

        function decToAscii(dec) {
            if (dec >= 32 && dec <= 126) {
                return String.fromCharCode(dec);
            }
            return '.';
        }

        // Re-added: Update Data Monitor content
        function updateDataMonitor(address, value, permissions = { manage: true, read: true, write: true }) {
            const hexAddress = address.toString(16).toUpperCase().padStart(4, '0');
            const hexValue = decToHex(value);
            const asciiChar = decToAscii(value);

            const getPermissionStatusHtml = (permType, hasPermission) => {
                const statusClass = hasPermission ? '' : 'red';
                const statusText = hasPermission ? '你拥有 (已设置密码)' : '无权限 / 已锁定';
                let permName = '';
                if (permType === 'manage') permName = '管理权限';
                if (permType === 'read') permName = '读权限';
                if (permType === 'write') permName = '写权限';
                return `<span class="permission-status ${statusClass}">${permName}: ${statusText}</span>`;
            };

            dataMonitor.innerHTML = `
                <h4>数据监视器</h4>
                <p>地址: <span class="monitor-address">0x${hexAddress} (${address})</span></p>
                <p>十进制值: <span class="monitor-value">${value}</span></p>
                <p>十六进制值: <span class="monitor-hex">0x${hexValue}</span></p>
                <p>ASCII字符: <span class="monitor-ascii">'${asciiChar}'</span></p>
                <hr style="border-color: var(--color-border-subtle); margin: 15px 0;">
                <h4>权限状态</h4>
                ${getPermissionStatusHtml('manage', permissions.manage)}
                ${getPermissionStatusHtml('read', permissions.read)}
                ${getPermissionStatusHtml('write', permissions.write)}
            `;
            showDataMonitor(); // Ensure monitor is visible when updated
        }

        // --- Monitor visibility functions ---
        function showDataMonitor() {
            if (!isMonitorVisible) {
                dataMonitorFloatingWrapper.classList.add('visible');
                isMonitorVisible = true;
            }
        }

        function hideDataMonitor() {
            if (isMonitorVisible) {
                dataMonitorFloatingWrapper.classList.remove('visible');
                isMonitorVisible = false;
            }
        }

        // --- Mouse follow for monitor ---
        document.addEventListener('mousemove', handleMouseMove);

        function handleMouseMove(event) {
            if (isMonitorVisible) {
                const monitorWidth = dataMonitorFloatingWrapper.offsetWidth;
                const monitorHeight = dataMonitorFloatingWrapper.offsetHeight;
                const margin = 20; // Offset from cursor
                const padding = 10; // Padding from window edges

                let newLeft = event.clientX + margin;
                let newTop = event.clientY + margin;

                // Adjust if it goes off screen (right)
                if (newLeft + monitorWidth > window.innerWidth - padding) {
                    newLeft = event.clientX - monitorWidth - margin;
                }
                // Adjust if it goes off screen (bottom)
                if (newTop + monitorHeight > window.innerHeight - padding) {
                    newTop = event.clientY - monitorHeight - margin;
                }
                // Adjust if it goes off screen (left)
                if (newLeft < padding) {
                    newLeft = padding;
                }
                // Adjust if it goes off screen (top)
                if (newTop < padding) {
                    newTop = padding;
                }

                dataMonitorFloatingWrapper.style.transform = `translate(${newLeft}px, ${newTop}px)`;
            }
        }


        function getOrCreateUserId() {
            let storedUserId = localStorage.getItem(USER_ID_STORAGE_KEY);
            let isFirstTime = false;

            if (!storedUserId) {
                const randomId = `player_${Math.random().toString(36).substring(2, 10)}`;
                localStorage.setItem(USER_ID_STORAGE_KEY, randomId);
                storedUserId = randomId;
                isFirstTime = true;
            }
            currentUserId = storedUserId;
            return { id: storedUserId, isFirstTime: isFirstTime };
        }

        function clearUserId() {
            if (confirm("清除用户ID?")) {
                localStorage.removeItem(USER_ID_STORAGE_KEY);
                for (let i = PRIVATE_RANGE_START; i <= PRIVATE_RANGE_END; i++) {
                    localStorage.removeItem(getByteStorageKey(i));
                }
                location.reload();
            }
        }

        function getByteStorageKey(address) {
            return `${BYTE_STORAGE_PREFIX}${currentUserId}_${address}`;
        }

        function getByteRaw(address) {
            const storedValue = localStorage.getItem(getByteStorageKey(address));
            let byteValue = 0;
            if (storedValue) {
                byteValue = parseInt(storedValue, 10);
                if (isNaN(byteValue) || byteValue < 0 || byteValue > 255) {
                    byteValue = 0;
                }
            }
            return byteValue;
        }

        function getByte(address, updateUI = true) {
            if (typeof address !== 'number' || address < PRIVATE_RANGE_START || address > PRIVATE_RANGE_END || !Number.isInteger(address)) {
                if (updateUI) {
                    bankResult.textContent = `地址 '${address}' 无效。`;
                    bankResult.classList.add('error');
                }
                return 0;
            }

            const byteValue = getByteRaw(address);

            if (updateUI) {
                bankResult.textContent = `读取: 地址 ${address} = ${byteValue}`;
                bankResult.classList.remove('error');
                const currentBox = document.querySelector(`.memory-box[data-address="${address}"]`);
                if (currentBox) {
                    const boxValueSpan = currentBox.querySelector('.box-value');
                    if (boxValueSpan) {
                        boxValueSpan.textContent = decToHex(byteValue);
                    }
                }
                // Re-added: Update data monitor
                updateDataMonitor(address, byteValue);
            }
            return byteValue;
        }

        function updateAsciiColumnForAddress(address) {
            const bytesPerRow = 16;
            const rowStartAddr = address - (address % bytesPerRow);
            const asciiRowDiv = document.querySelector(`#memoryAsciiColumn div[data-row-start="${rowStartAddr}"]`);
            if (asciiRowDiv) {
                let asciiString = '';
                for (let i = 0; i < bytesPerRow; i++) {
                    const currentAddr = rowStartAddr + i;
                    if (currentAddr > PRIVATE_RANGE_END) {
                        asciiString += ' ';
                        continue;
                    }
                    asciiString += decToAscii(getByteRaw(currentAddr));
                }
                asciiRowDiv.textContent = asciiString;
            }
        }

        function setByte(address, value) {
            if (typeof address !== 'number' || address < PRIVATE_RANGE_START || address > PRIVATE_RANGE_END || !Number.isInteger(address)) {
                bankResult.textContent = `地址 '${address}' 无效。`;
                bankResult.classList.add('error');
                return `地址 '${address}' 无效。`;
            }
            if (typeof value !== 'number' || value < 0 || value > 255 || !Number.isInteger(value)) {
                bankResult.textContent = `值 '${value}' 无效。`;
                bankResult.classList.add('error');
                return `值 '${value}' 无效。`;
            }

            try {
                localStorage.setItem(getByteStorageKey(address), value.toString());
                bankResult.textContent = `写入: 地址 ${address} = ${value}`;
                bankResult.classList.remove('error');

                const boxToUpdate = document.querySelector(`.memory-box[data-address="${address}"]`);
                if (boxToUpdate) {
                    const boxValueSpan = boxToUpdate.querySelector('.box-value');
                    if (boxValueSpan) {
                        boxValueSpan.textContent = decToHex(value);
                    }
                    updateAsciiColumnForAddress(address);
                }
                // Re-added: Update data monitor
                updateDataMonitor(address, value);
                return `写入: 地址 ${address} = ${value}`;
            } catch (e) {
                bankResult.textContent = `写入失败：${e.message}`;
                bankResult.classList.add('error');
                return `写入失败：${e.message}`;
            }
        }

        function selectAddressInGrid(address) {
            selectedAddress = address;
            bankAddressInput.value = address;
            // 移除所有格子的 current-address 类
            document.querySelectorAll('.memory-box').forEach(b => b.classList.remove('current-address'));
            // 为当前选定的格子添加 current-address 类
            const currentBox = document.querySelector(`.memory-box[data-address="${address}"]`);
            if (currentBox) {
                currentBox.classList.add('current-address');
            }
            getByte(address, true); // 这会调用 updateDataMonitor
        }

        async function renderPrivateMemoryGrid() {
            privateMemoryGrid.innerHTML = '';
            memoryAddressColumn.innerHTML = '';
            memoryAsciiColumn.innerHTML = '';

            const bytesPerRow = 16;
            for (let rowStart = PRIVATE_RANGE_START; rowStart <= PRIVATE_RANGE_END; rowStart += bytesPerRow) {
                const addressLabel = document.createElement('div');
                addressLabel.classList.add('memory-row-address');
                addressLabel.textContent = `0x${rowStart.toString(16).toUpperCase().padStart(4, '0')}`;
                memoryAddressColumn.appendChild(addressLabel);

                const currentRowAsciiBytes = [];
                for (let i = 0; i < bytesPerRow; i++) {
                    const currentAddress = rowStart + i;
                    if (currentAddress > PRIVATE_RANGE_END) {
                        const emptyBox = document.createElement('div');
                        emptyBox.classList.add('memory-box');
                        emptyBox.style.visibility = 'hidden';
                        privateMemoryGrid.appendChild(emptyBox);
                        currentRowAsciiBytes.push(-1);
                        continue;
                    }

                    const value = getByteRaw(currentAddress);
                    currentRowAsciiBytes.push(value);

                    const box = document.createElement('div');
                    box.classList.add('memory-box', 'private-box', 'current-user');
                    box.setAttribute('data-address', currentAddress);

                    // 初始渲染时，如果当前格子是 selectedAddress，则添加 current-address 类
                    if (currentAddress === selectedAddress) {
                        box.classList.add('current-address');
                    }

                    const boxValueSpan = document.createElement('span');
                    boxValueSpan.classList.add('box-value');
                    boxValueSpan.textContent = decToHex(value);
                    box.appendChild(boxValueSpan);

                    const keyIndicators = document.createElement('div');
                    keyIndicators.classList.add('key-indicators');
                    keyIndicators.innerHTML = `
                        <span class="key-manage"></span>
                        <span class="key-read"></span>
                        <span class="key-write"></span>
                    `;
                    box.appendChild(keyIndicators);

                    // 移除了 box.addEventListener('click', ...)
                    privateMemoryGrid.appendChild(box);
                }

                const asciiLabel = document.createElement('div');
                asciiLabel.classList.add('memory-row-ascii');
                asciiLabel.setAttribute('data-row-start', rowStart);
                asciiLabel.textContent = currentRowAsciiBytes.map(byte => byte === -1 ? ' ' : decToAscii(byte)).join('');
                memoryAsciiColumn.appendChild(asciiLabel);
            }
        }

        // 修改 writeButton 的事件监听器，使其在写入后更新选定地址
        writeButton.addEventListener('click', () => {
            const address = parseInt(bankAddressInput.value);
            const value = parseInt(bankValueInput.value);
            setByte(address, value); // 这会调用 updateDataMonitor
            selectAddressInGrid(address); // 确保写入后，该地址成为选定地址并更新 UI
        });


        // ==========================================================
        // 新增/修改：事件委托和数据监视器交互逻辑
        // ==========================================================

        // 鼠标悬停在内存格子上时，更新并显示数据监视器
        privateMemoryGrid.addEventListener('mouseover', (event) => {
            let targetBox = event.target.closest('.memory-box'); // 查找最近的 .memory-box 父级
            if (targetBox && targetBox.getAttribute('data-address')) { // 确保是有效的内存单元
                const currentAddress = parseInt(targetBox.getAttribute('data-address'));
                const value = getByteRaw(currentAddress); // 使用 getByteRaw 获取原始值，避免触发 UI 更新
                // 默认权限为 true，因为这是用户自己的私有内存
                const permissions = { manage: true, read: true, write: true }; 
                updateDataMonitor(currentAddress, value, permissions);
                showDataMonitor();
            }
        });

        // 鼠标离开整个内存显示区域时，隐藏数据监视器
        memoryViewerWrapper.addEventListener('mouseleave', () => {
            hideDataMonitor();
        });

        // 使用事件委托处理内存格子的点击事件，以选择地址
        privateMemoryGrid.addEventListener('click', (event) => {
            let targetBox = event.target.closest('.memory-box');
            if (targetBox && targetBox.getAttribute('data-address')) { // 确保是有效的内存单元
                const currentAddress = parseInt(targetBox.getAttribute('data-address'));
                selectAddressInGrid(currentAddress); // 这将处理 current-address 类的添加/移除
            }
        });

        // ==========================================================
        // end of 新增/修改
        // ==========================================================


        function initializeApp() {
            const user = getOrCreateUserId();
            if (user.isFirstTime) {
                loginStatus.textContent = `ID生成 (${user.id})`;
                loginStatus.classList.add('first-time');
            } else {
                loginStatus.textContent = `ID已载入 (${user.id})`;
                loginStatus.classList.add('revisit');
            }
            userIdDisplay.textContent = user.id;
            privateRangeDisplay.textContent = `${PRIVATE_RANGE_START} ~ ${PRIVATE_RANGE_END}`;


            bankAddressInput.min = PRIVATE_RANGE_START;
            bankAddressInput.max = PRIVATE_RANGE_END;
            bankAddressInput.value = PRIVATE_RANGE_START;

            renderPrivateMemoryGrid();
            selectAddressInGrid(PRIVATE_RANGE_START); // 这将使监视器可见并显示初始地址
        }

        initializeApp();
    </script>
</body>
</html>